import Vue from 'vue'
import cache from 'commons/cache'
import * as constants from 'src/AppConstants'
import * as types from './mutation-types'
import navigate from 'config/navigate'

/**
 * 登录
 * @param payload 用户名和密码
 */
export const login = function ({commit}, payload) {
    return Vue.axios.post('/sys/sysuser/login', payload).then((resp) => {
        let apiToken = resp.headers[constants.API_TOKEN]
        let userInfo = resp.data.data
        commit(types.UPDATE_TOKEN, apiToken)
        commit(types.UPDATE_USER_INFO, userInfo)
        commit(types.UPDATE_NAVS, navigate)
        cache.setValue(constants.CACHE_USER_INFO, JSON.stringify(userInfo))
        cache.setValue(constants.CACHE_API_TOKEN, apiToken)
        cache.setValue(constants.CACHE_USER_NAV, JSON.stringify(navigate))
        return userInfo
    }).catch((err) => {
        return Promise.reject(err)
    })
}

/**
 * 退出登录
 * @param context
 */
export const logout = function ({commit}, fromLocal) {
    if (fromLocal) {
        _logout(commit)
        return Promise.resolve(true)
    }
    return Vue.axios.post('/sys/sysuser/logout').then((resp) => {
        _logout(commit)
        return resp.data
    }).catch((err) => {
        return Promise.reject(err)
    })
}

const _logout = function (commit) {
    commit(types.UPDATE_TOKEN, '')
    commit(types.UPDATE_USER_INFO, '')
    commit(types.UPDATE_NAVS, [])
    cache.removeKey(constants.CACHE_USER_INFO)
    cache.removeKey(constants.CACHE_API_TOKEN)
    cache.removeKey(constants.CACHE_USER_NAV)
}
